package com.friday.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBUtil {
	private static DBUtil util = null;
	private Properties info = new Properties();

	private DBUtil() throws Exception {
		InputStream is = null;
		try {
			is = this.getClass().getResourceAsStream(
					"/com/friday/cfg/DBConfig.properties");
			info.load(is);
		} catch (Exception e) {
			throw new Exception("error!");
		} finally {
			if (is != null) {
				is.close();
			}
		}
	}

	public static DBUtil newInstance() throws Exception {
		synchronized (DBUtil.class) {
			if (util == null) {
				util = new DBUtil();
			}
		}

		return util;
	}

	public Connection getConnection() throws Exception {
		Class.forName(info.getProperty("driver"));
		return DriverManager.getConnection(info.getProperty("url"), info
				.getProperty("username"), info.getProperty("password"));
	}

	public void close(Connection conn)  {
		try {
			if (conn != null && !conn.isClosed()) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void close(Statement stmt) {
		try {
			if (stmt != null) {
				stmt.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void close(PreparedStatement pStmt) {
		try {
			if (pStmt != null) {
				pStmt.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void close(ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}